import richiesta
import rete
import io
import os, sys
import config
class RispostaWSGI:
	def __init__(self, richiesta):
		self.richiesta = richiesta
		self.tocchi = []
		self.totLen = 0
	def __call__(self, status, headers, exc_info=None): 
		self.status = status
		self.h = headers
		return self.scrivi
	def scrivi(self,testo):
		self.tocchi.append(testo)
		self.totLen += len(testo)
	def manda(self):
		self.h.append(('Content-Length',str(self.totLen)))
		richiesta.mandaHeaders(self.richiesta, self.status, self.h) 
		for write in self.tocchi:
			rete.scrivi(self.richiesta.connessione, write)

def convertiHeaders(headersWSGI):
	d = dict()
	for elem in headersWSGI:
		d[elem[0]] = ", ".join(elem[1:])
	return d

def prepare_environ(req,httpVer,scriptName=""):
	content, headerSection = req.contenuto, req.headers
	environ = dict(os.environ.items())
	environ['wsgi.input']        = io.BytesIO(content)
	environ['wsgi.errors']       = sys.stderr
	environ['wsgi.version']      = (1, 0)
	environ['wsgi.multithread']  = False
	environ['wsgi.multiprocess'] = False
	environ['wsgi.url_scheme']   = 'http'
	environ['REQUEST_METHOD']    = headerSection.method
	environ['SCRIPT_NAME']	     = scriptName		#scriptName resta il percorso del gestore
	environ['PATH_INFO'] 		 = headerSection.resource.partition(scriptName)[2]	#questo è il resto
	environ['QUERY_STRING']	 	 = headerSection.queryString
	#print("----- "+ headerSection.resource)
	#print("-----... "+ scriptName)
	environ['CONTENT_TYPE']		 = headerSection.get("content-type")
	environ['CONTENT_LENGTH']	 = headerSection.get("content-length")
	environ['SERVER_NAME']		 = req.headers.hostName
	environ['SERVER_PORT']		 = req.headers.port
	environ['SERVER_PROTOCOL']	 = httpVer
	for h in headerSection.headers:
		environ['HTTP_' + h[0].upper().replace("-","_")] = h[1]
	return environ
